package edu.mse.camel.client.posterboard.ui.treeoutline;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.dnd.AbstractTransferDragSourceListener;
import org.eclipse.jface.util.TransferDragSourceListener;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.Transfer;

import com.cea.papyrus.core.dnd.ObjectTransfer;
import com.cea.papyrus.core.treeeditpart.DiagramTreeEditPart;
import com.cea.papyrus.core.treeeditpart.ElementTreeEditPart;

import edu.mse.camel.client.whiteboard.gef.ui.editpart.WhiteboardDiagramTreeEditPart;

//TODO: Auto-generated Javadoc
/**
 * The Class TreeOutlinePageDragSourceListener.
 * 
 * @author Chokri Mraidha
 */
public class PBTreeOutlinePageDragSourceListener 
		extends AbstractTransferDragSourceListener 
		implements TransferDragSourceListener {

	/**
	 * The tree viewer.
	 */
	private EditPartViewer treeViewer;

	/**
	 * 
	 */
	private List transferData;

	/**
	 * The Constructor.
	 * 
	 * @param viewer the viewer
	 */
	public PBTreeOutlinePageDragSourceListener(EditPartViewer viewer){
		super(viewer,ObjectTransfer.getInstance());
		treeViewer = viewer;
	}

	/**
	 * Drag set data.
	 * 
	 * @param event the event
	 */
	public void dragSetData(DragSourceEvent event){
		event.data=getSelection();
	}

	/**
	 * Gets the transfer.
	 * 
	 * @return the transfer
	 */
	public Transfer getTransfer() {
		return ObjectTransfer.getInstance();
	}

	/**
	 * Drag start.
	 * 
	 * @param event the event
	 */
	public void dragStart(DragSourceEvent event){
		List data = getSelection();
		if (data.isEmpty())
			event.doit = false;
		(ObjectTransfer.getInstance()).setObject(data);
	}

	/**
	 * Drag finished.
	 * 
	 * @param event the event
	 */
	public void dragFinished(DragSourceEvent event){
		transferData = null;
		ObjectTransfer.getInstance().setObject(null);
	}

	/**
	 * @return 
	 */
	protected List getSelection() {
		List selection = treeViewer.getSelectedEditParts();
		transferData = new ArrayList();
		for (int i = 0; i < selection.size(); i++) {
			if(((EditPart)selection.get(i)) instanceof ElementTreeEditPart ){
				transferData.add(((EditPart)selection.get(i)).getModel());
			}
			//Darpan
			if (((EditPart)selection.get(i)) instanceof DiagramTreeEditPart) {
				transferData.add(((EditPart)selection.get(i)).getModel());
			}
			//Darpan
			// can only drag elements, not diagrams or group of elements
			if(((EditPart)selection.get(i)) instanceof WhiteboardDiagramTreeEditPart ){
				transferData.add(((EditPart)selection.get(i)).getModel());
			}
		}
		return transferData;
	}
}
